<?php


namespace app\common\cachemodel\zl3;


use app\common\lib\Util;
use app\common\model\BaseCache;
use think\Exception;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl3FortuneYearAnalysis extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl3_fortune_year_analysis';

    protected $cacheModel = 'fortune.fortune_year_analysis';

    /**
     * 添加并入队
     * @param $data
     * @return false|int
     */
    public function SaveDataAndQueue(array $data = [])
    {
        // $data = [
        //     'uid' => '',
        //     'rid' => '',
        //     'type' => '',    // 类型  1=>一生起伏 2=>人生阶段 3=>年运筛查
        //     'hash' => '',    //  Util::getRecodeHashKey($recode) 调用该方法获取
        //     'status' => 1,   // 计算状态 1=>计算中 2=>计算完成 3=>计算失败
        //     'order_num' => '',   // 订单编号
        //     'stageyear' => 0,    // type=2    20172026
        //     'stage_num' => 0,    // 2
        //     'recode_info' => 0,  // 档案信息  json_encode
        // ];
        try
        {
            $id = $this->insertGetId([
                'uid' => $data['uid'],
                'rid' => $data['rid'],
                'type' => $data['type'],
                'hash' => $data['hash'],
                'status' => $data['status'],
                'order_num' => $data['order_num'],
                'stageyear' => $data['stageyear'],
                'stage_num' => $data['stage_num'],
                'recode_info' => $data['recode_info'],
                'create_time' => time(),
            ]);
            // 删除缓存
            $key = $data['uid'] . ':' . $data['rid'];
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->rmCache();
            // 发送 计算队列
            Util::queuePush('fortune_year_analysis_calculate', ['id' => $id], 30);
        }
        catch (\Exception $e)
        {
            Log::write('Zl3FortuneYearAnalysis model => SaveDataAndQueue()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
        return (int)$id;
    }

    /**
     * 重新计算
     * @param int $id
     * @param int $uid
     * @param int $rid
     * @param array $data
     * @return bool
     */
    public function UpdateDataAndQueue(int $id, int $uid, int $rid, array $data): bool
    {
        try
        {
            $this->where('id', $id)->update($data);
            // 删除缓存
            $key = $uid . ':' . $rid;
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->rmCache();
            // 发送 计算队列
            Util::queuePush('fortune_year_analysis_calculate', ['id' => $id], 30);
            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl3FortuneYearAnalysis model => UpdateDataAndQueue()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取订单备份档案信息
     * @param string $order_id
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getOrderRecodeBackRecode($order_id)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('details_back_recode', $order_id)->getDataAndSet(function () use ($order_id)
        {
            try
            {
                return $this
                    ->where(['order_num' => $order_id])
                    ->group('order_num')
                    ->column('recode_info', 'id');
            }
            catch (\Exception $e)
            {
                return [];
            }
        }, [], 'details_back_recode');
    }

    /**
     * 获取用户档案解锁 运势报告信息
     * @param array $recode
     * @param array $field
     * @param int $year
     * @param array $stageyearData
     * @return array
     * @throws \Exception
     */
    public function getFortuneAnalysis(array $recode, $field = [], $year = 0, array $stageyearData = ['num' => 0])
    {
        $recodeHashKey = Util::getRecodeHashKey($recode);
        if ($stageyearData['num'] === 0)
        {   // 如果  本次人生阶段 不在有效范围内 则 不取人生阶段数据
            if ($field)
            {
                foreach ($field as $k => $v)
                {
                    if ($v == 2) unset($field[$k]);
                }
                if (empty($field))
                {
                    return [2 => []];
                }
            } else
            {
                $field = [1, 3];
            }
        }
        $reportData = $this->getFortuneAnalysisALL($recode['uid'], $recode['id'], $field);
        if ($field)
        {
            $reportData = array_filter($reportData);
        }
        foreach ($reportData as $type => $reportDatum)
        {
            if ($type == 2)
            {
                if ($stageyearData['num'] === 0)
                {
                    $reportData[$type] = [];
                    continue;
                }
                $stageyear = $stageyearData['start_year'] . $stageyearData['end_year'];
                if (isset($reportDatum[$recodeHashKey][$stageyear]))
                {
                    $reportDatum[$recodeHashKey][$stageyear]['recode_is_change'] = false;
                    $reportData[$type] = $reportDatum[$recodeHashKey][$stageyear];
                    continue;
                }
                $d = [];
                foreach ($reportDatum as $hashKey => $reportDatumItem)
                {
                    if ($recodeHashKey === $hashKey)
                    {
                        continue;
                    } else
                    {
                        foreach ($reportDatumItem as $item)
                        {
                            $stageyearItem = (string)$item['stageyear'];
                            $sT = substr($stageyearItem, 0, 4);
                            $eT = substr($stageyearItem, 4, 4);
                            if ($sT <= $year && $eT >= $year)
                            {   // 已解锁当前年阶段
                                if ($d)
                                {
                                    if ($item['id'] > $d['id'])
                                    {
                                        $item['recode_is_change'] = true;
                                        $d = $item;
                                    }
                                } else
                                {
                                    $item['recode_is_change'] = true;
                                    $d = $item;
                                }
                                break;
                            }
                        }
                    }
                }
                $reportData[$type] = $d;
            } else
            {
                if (isset($reportDatum[$recodeHashKey]))
                {
                    $reportDatum[$recodeHashKey]['recode_is_change'] = false;
                    $reportData[$type] = $reportDatum[$recodeHashKey];
                    continue;
                }

                $resData = [];
                foreach ($reportDatum as $reportDatumItem)
                {
                    if (empty($resData))
                    {
                        $resData = $reportDatumItem;
                    } else
                    {
                        if ($reportDatumItem['id'] > $resData['id'])
                        {
                            $resData = $reportDatumItem;
                        }
                    }
                }

                $resData['recode_is_change'] = true;

                $reportData[$type] = $resData;
            }
        }

        return $reportData;
    }

    /**
     * 通过订单 获取解锁信息
     * @param $uid
     * @param $rid
     * @param $orderId
     * @param array $field
     * @return array|mixed
     * @throws \Exception
     */
    public function getOrderFortuneAnalysis($uid, $rid, $orderId, $field = [])
    {
        $reportData = $this->getFortuneAnalysisALL($uid, $rid, $field);

        $resData = [];
        foreach ($reportData as $type => $reportDataLists)
        {
            if ($type === 2)
            {
                foreach ($reportDataLists as $reportDetailsItem)
                {
                    foreach ($reportDetailsItem as $item)
                    {
                        if ($item['order_num'] === $orderId)
                        {
                            $item['recode_is_change'] = false;
                            $resData = $item;
                            break(2);
                        }
                    }
                }
            } else
            {
                foreach ($reportDataLists as $reportDetailsItem)
                {
                    if ($reportDetailsItem['order_num'] === $orderId)
                    {
                        $reportDetailsItem['recode_is_change'] = false;
                        $resData = $reportDetailsItem;
                        break;
                    }
                }
            }
        }

        return $resData;
    }

    /**
     * 获取用户档案解锁数据详情
     * @param $uid
     * @param $rid
     * @param array $field
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getFortuneAnalysisALL($uid, $rid, $field = [])
    {
        $key = $uid . ':' . $rid;

        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->getDataAndSet(function () use ($uid, $rid)
        {
            return $this->getFortuneAnalysisByDb($uid, $rid);
        }, $field);

        if ($data && $field && is_string($data))
        {
            $data = [current($field) => json_decode($data, true)];
        } else
        {
            foreach ($data as $gid => $valueStr)
            {
                $data[$gid] = json_decode($valueStr, true);
            }
        }

        return $data;
    }

    /**
     * 通过数据库 获取数据
     * @param $uid
     * @param $rid
     * @return array
     */
    protected function getFortuneAnalysisByDb($uid, $rid): array
    {
        try
        {
            $data = $this->where(['uid' => $uid, 'rid' => $rid])->order('id asc')->column('uid,type,hash,order_num,content,status,stageyear,stage_num,recode_info,create_time', 'id');

            $resData = [];
            foreach ($data as $key => $value)
            {
                $value = arrayKeyData2int($value, ['id', 'uid', 'type', 'status', 'stageyear', 'stage_num', 'create_time']);
                $value['content'] = $value['content'] ? json_decode($value['content'], true) : [];
                $value['recode_info'] = $value['recode_info'] ? json_decode($value['recode_info'], true) : [];
                if ($value['type'] == 2)
                {
                    $resData[$value['type']][$value['hash']][$value['stageyear']] = $value;
                } else
                {
                    $resData[$value['type']][$value['hash']] = $value;
                }
            }

            foreach ($resData as $gid => $resDatum)
            {
                $resData[$gid] = json_encode($resDatum, JSON_UNESCAPED_UNICODE);
            }
        }
        catch (Exception $e)
        {
            $resData = [];
        }

        return $resData;
    }
}
